package pers.dawnyang.modular.system.service.impl;

import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import eu.bitwalker.useragentutils.UserAgent;
import pers.dawnyang.common.constant.Const;
import pers.dawnyang.common.domain.entity.SysLoginLog;
import pers.dawnyang.common.util.web.IPUtil;
import pers.dawnyang.modular.system.mapper.SysLoginLogMapper;
import pers.dawnyang.modular.system.service.LoginService;

@Service
public class LoginServiceImpl implements LoginService {

  @Autowired
  private SysLoginLogMapper sysLoginLogMapper;


  @Async("threadPoolTaskExecutor")
  @Override
  public void recordLogin(SysLoginLog loginLog) {
    /*
     * System.out.println("准备同步记录"); try {
     * Thread.sleep(10000); } catch
     * (InterruptedException e) { // TODO
     * Auto-generated catch block
     * e.printStackTrace(); }
     * System.out.println("同步开始");
     */
    sysLoginLogMapper.insert(loginLog);
  }

  @Override
  public SysLoginLog setLoginInfo(HttpServletRequest request, String userCode, Integer loginType,
      Integer loginStatus, String msg) {
    HttpSession httpSession = request.getSession(true);
    String loginIp = IPUtil.getIpAddr(request);
    UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
    String os = userAgent.getOperatingSystem().getName();
    String browser = userAgent.getBrowser().getName();
    SysLoginLog loginLog = new SysLoginLog();
    loginLog.setUserCode(userCode);
    loginLog.setLoginIp(loginIp);
    loginLog.setBrowser(browser);
    loginLog.setOs(os);
    loginLog.setLoginTime(new Date());
    loginLog.setLoginType(loginType);
    loginLog.setLoginStatus(loginStatus);
    loginLog.setMsg(msg);
    if (loginStatus.equals(Const.LOGIN_SUCCESS)) {
      loginLog.setSessionId(httpSession.getId());
    }
    return loginLog;
  }



}
